import os
from PIL import Image
from ftplib import FTP
import django.utils.timezone as timezone
from server.config import FTP_SERVER_AZURE, FTP_SERVER_COMPRESS_AZURE, FTP_SERVER_REVIEW_AZURE, FTP_SERVER_REVIEW_COMPRESS_AZURE
from server.models import Picture, WaitedReviewPicture
import time


def add_server_address(idx, image_name, is_waited_review=False):
    if not is_waited_review:
        return "{}{}".format(FTP_SERVER_COMPRESS_AZURE, compress_img(image_name))
    else:
        return "{}{}".format(FTP_SERVER_REVIEW_COMPRESS_AZURE, compress_img(image_name))


def fix_server(idx, picture):
    return {'url': "{}{}".format(FTP_SERVER_COMPRESS_AZURE, compress_img(picture.image_name)),
            'id': picture.id}


def compress_img(img_name):
    # 后缀改为.jpg
    return img_name.rstrip(".png") + ".jpg"


def get_ip(request):
    '''获取请求者的IP信息'''
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
    else:
        ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
    return ip


def remove_tag(file_name):
    """file_name命名规则为 （序号-随机种子-正面tag） """
    file_name_split = file_name.split("-")
    if len(file_name_split) >= 3:
        return file_name_split[0] + "-" + file_name_split[1] + ".png"
    else:
        return file_name


def write_file(file):
    base_path = './tmp/img'
    if not os.path.exists(base_path):
        # os.umask(000)
        os.makedirs(base_path, mode=0o777)
    file_name = remove_tag(file._get_name())
    file_path = os.path.join(base_path, file_name)
    compress_file_name = file_name.replace(".png", ".jpg")
    compress_file_path = os.path.join(base_path, compress_file_name)
    with open(file_path, "wb+") as f:
        if file.multiple_chunks():
            for content in file.chunks():
                f.write(content)
        else:
            data = file.read()  # .decode('utf-8')
            f.write(data)  # 保存原图
        img = Image.open(file_path)
        img = img.convert('RGB')
        img.save(compress_file_path, quality=75)  # 转为jpg格式的图片，质量为75，实现压缩图片的效果
        img.close()


class FtpHandler:
    def __init__(self):
        self.image_path = '/novalai'
        self.compress_image_path = '/compress_novalai'

    def create_ftp_server(self, ip, port, username, pw):
        ftp_server = FTP()
        ftp_server.connect(ip, port)
        ftp_server.login(username, pw)
        ftp_server.getwelcome()
        ftp_server.encoding = "utf-8"
        return ftp_server

    # def list_dir(self):
    #     print(self.ftp_server.dir())

    def add_image(self, file):
        ftp_servers = {}
        try:
            base_path = './tmp/img'
            file_name = remove_tag(file._get_name())
            res = Picture.objects.filter(image_name=file_name)
            if not res.exists():
                write_file(file)  # 保存图片为临时文件
                file_path = os.path.join(base_path, file_name)
                Picture.objects.create(image_name=file_name, create_time=int(round(time.time() * 1000)),
                                       prefix='novalai')
                print('数据库写入成功')
                ftp_servers['azure'] = self.create_ftp_server("20.205.38.73", 21, "b8313", "b8313313")
                # ftp_servers['server'] = self.create_ftp_server("server.masaikk.xyz", 21, "b8313", "b8313")
                for key, ftp_server in ftp_servers.items():
                    ftp_server.cwd(self.image_path)
                    fp = open(file_path, 'rb')
                    ftp_server.storbinary('STOR {}'.format(file_name), fp)
                    fp.close()
                    print('{}服务器上传原图'.format(key))
                    compress_file_name = file_name.split(".")[0] + ".jpg"
                    compress_file_path = os.path.join(base_path, compress_file_name)
                    ftp_server.cwd(self.compress_image_path)
                    fp = open(compress_file_path, 'rb')
                    ftp_server.storbinary('STOR {}'.format(compress_file_name), fp)
                    fp.close()
                    print('{}服务器上传压缩图片'.format(key))
                    ftp_server.quit()
                    ftp_server.close()
            else:
                print('数据库已存在该图片，跳过')
        except Exception as e:
            print("上传失败：", e)

    def rename_pic(self, pic):
        ftp_servers = {}
        try:
            ftp_servers['azure'] = self.create_ftp_server("azure.masaikk.fun", 21, "b8313", "b8313313")
            # ftp_servers['server'] = self.create_ftp_server("server.masaikk.fun", 21, "b8313", "b8313")
            base_source_path = './server_image/'
            base_compress_source_path = './server_image_compress/'
            base_target_path = './novalai/'
            base_compress_target_path = './compress_novalai/'
            for key, ftp_server in ftp_servers.items():
                ftp_server.rename(base_source_path + pic.image_name, base_target_path + pic.image_name)
                ftp_server.rename(base_compress_source_path + compress_img(pic.image_name),
                                  base_compress_target_path + compress_img(pic.image_name))
            Picture.objects.create(image_name=pic.image_name, uuid=pic.uuid, tags=pic.tags,
                                   negative_tags=pic.negative_tags)
            print('数据库写入成功')
        except Exception as e:
            print("移动失败：", e)
